import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { usePermissionStore } from "./permission"
import { useTagsViewStore } from "./tags-view"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import router, { resetRouter, asyncRoutes } from "@/router"
import { loginApi, getUserInfoApi } from "@/api/login"
import { type ILoginRequestData } from "@/api/login/types/login"
import { type RouteRecordRaw } from "vue-router"
import asyncRouteSettings from "@/config/async-route"
import { admin } from "@/router"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  const username = ref<string>("")
  const teamName = ref<string>("")
  const usernameID = ref<string>("")
  const password = ref<string>("")
  const userrole = ref<string>("")
  const nickName = ref<string>("")
  const department = ref<string>("")
  const userMoney = ref<number>(NaN)
  const usermaxOrder = ref<number>(NaN)
  const permissionStore = usePermissionStore()
  const tagsViewStore = useTagsViewStore()
  const userInfo = ref<any>()

  // 多团队数据 roleList
  const roleList = ref<any>([])
  const setroleList = (value: any) => {
    roleList.value = value
  }
  // 宽带订单未提交数量
  const NOKDTj = ref<any>("")
  const setNOKDTj = (value: any) => {
    NOKDTj.value = value
  }
  // 长链接未处理
  const tswcl = ref<any>("")
  const NOtswcl = (value: any) => {
    tswcl.value = value
  }
  // 长链接处理中
  const tsclz = ref<any>("")
  const NOtsclz = (value: any) => {
    tsclz.value = value
  }

  /** 设置角色数组 */
  const setRoles = (value: string[]) => {
    roles.value = value
  }
  /** 登录 */
  const login = (loginData: ILoginRequestData) => {
    return new Promise((resolve, reject) => {
      loginApi({
        username: loginData.username,
        password: loginData.password,
        code: loginData.code,
        uuid: loginData.uuid
      })
        .then((res) => {
          setToken(res.data.token)
          token.value = res.data.token
          resolve(true)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  /** 获取用户详情 */
  const getInfo = () => {
    return new Promise((resolve, reject) => {
      getUserInfoApi()
        .then((res) => {
          const data = res.data
          userInfo.value = data
          usernameID.value = data.user.id
          username.value = data.user.name
          teamName.value = data.user.team
          password.value = data.user.password
          userrole.value = data.user.role
          nickName.value = data.user.nickName
          department.value = data.user.department
          userMoney.value = data.user.money
          usermaxOrder.value = data.user.maxOrder
          roleList.value = data.user.roleList
          console.log(data.user, "------??")
          // console.log(username.value, "123------")
          // console.log(usermaxOrder.value, "123------")
          // 验证返回的 roles 是否是一个非空数组
          const role = [data.user.role]
          const auth = data.role?.powerList?.split(",")
          // console.log(asyncRoutes)
          const powerRoutes = asyncRoutes.slice(0, asyncRoutes.length - 1)
          filterRoutes(powerRoutes, auth, role)
          if (role && role.length > 0) {
            roles.value = role
          } else {
            // 塞入一个没有任何作用的默认角色，不然路由守卫逻辑会无限循环
            roles.value = asyncRouteSettings.defaultRoles
            // console.log(asyncRouteSettings.defaultRoles)
          }
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // ------  页面权限-------------

  const filterRoutes = (routes: any, pList: any, role: string[]) => {
    if (role.join(",") !== admin) {
      routes.forEach((route: any) => {
        const r = { ...route }
        if (r.children) {
          r.children = filterRoutes(r.children, pList, role)
          r.meta.roles = role
        }
        if (pList.includes(r.name)) {
          r.meta.roles = role
        }
      })
    }
  }
  /** 切换角色 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    await getInfo()
    permissionStore.setRoutes(roles.value)
    resetRouter()
    permissionStore.dynamicRoutes.forEach((item: RouteRecordRaw) => {
      router.addRoute(item)
    })
    _resetTagsView()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
    window.location.reload()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 visited views 和 cached views */
  const _resetTagsView = () => {
    tagsViewStore.delAllVisitedViews()
    tagsViewStore.delAllCachedViews()
  }

  return {
    token,
    roles,
    username,
    teamName,
    userrole,
    usernameID,
    password,
    nickName,
    userMoney,
    usermaxOrder,
    department,
    roleList,
    userInfo,
    NOKDTj,
    tswcl,
    tsclz,
    NOtswcl,
    NOtsclz,
    setRoles,
    login,
    getInfo,
    changeRoles,
    logout,
    setroleList,
    setNOKDTj,
    resetToken
  }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
